﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using DFGK.IRepository;
using DFGK.IRepository.BBS;
using DFGK.IService.BBS;
using DFGK_WMS.Model.Models.BBS;

namespace DFGK.Service.BBS
{
    public class BBS_PostService : BaseService, IBBS_PostService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IBBS_PostRepository _bbs_PostRepo;

        public BBS_PostService(IUnitOfWork unitOfWork, IMapper mapper, IBBS_PostRepository bbs_PostRepo) : base(mapper)
        {
            _unitOfWork = unitOfWork;
            _bbs_PostRepo = bbs_PostRepo;
        }

        public List<BBS_Post> GetPageData(string? title, int? status, int pageIndex, int pageSize, out int totalCount)
        {
            var query = _bbs_PostRepo.GetEntityAll();
            if (!string.IsNullOrEmpty(title))
            {
                query = query.Where(t => t.Title.Contains(title));
            }
            if (status != null)
            {
                query = query.Where(t => t.Status == status);
            }
            totalCount = query.Count();
            query = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).OrderByDescending(o => o.Id);
            return query.ToList();
        }

        public bool SubmitPostData(BBS_Post post, out string msg)
        {
            msg = "";
            if (post.Id > 0)
            {
                _bbs_PostRepo.UpdEntity(post);
            }
            else
            {
                _bbs_PostRepo.AddEntity(post);
            }
            return _unitOfWork.SaveChangesEntity();
        }

        public bool DelBBS_Post(long postId, out string msg)
        {
            msg = "";
            var post = _bbs_PostRepo.QueryEntityById(postId);
            if (post == null)
            {
                msg = "参数错误";
                return false;
            }
            _bbs_PostRepo.DelEntity(post);
            return _unitOfWork.SaveChangesEntity();
        }
        public BBS_Post? GetPost(long postId)
        {
            return _bbs_PostRepo.QueryEntityById(postId);
        }

        public bool UpdateStatus(long id, out string msg)
        {
            msg = "";
            var obj = _bbs_PostRepo.QueryEntityById(id);
            if(obj == null)
            {
                msg = "单据不存在！";
                return false;
            }
            if(obj.Status == 0)
            {
                obj.Status = 1;
                _bbs_PostRepo.UpdEntity(obj);
                _unitOfWork.SaveChangesEntity();
            }
            return true;
        }
    }
}
